﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using BSF.Db;
using HuntingFishGame.ManageDomain.Model.User;

namespace HuntingFishGame.ManageDomain.DAL.User
{
	/// <summary>
    /// 数据访问类:OnlineUser
	/// </summary>
    public partial class OnlineUserDal
	{
		/// <summary>
		/// 是否存在该记录
		/// </summary>
        public bool Exists(DbConn pubConn, long ID)
        {
            return SqlHelper.Visit(ps =>
            {
                ps.Add("ID", ID);
                string strSql = "select count(1) from auth_OnlineUsers where ID=@ID";
                return LibConvert.ObjToInt(pubConn.ExecuteScalar(strSql.ToString(), ps.ToParameters())) > 0;
            });
        }

		/// <summary>
		/// 增加一条数据
		/// </summary>
        public long Add(DbConn pubConn, OnlineUserModel model)
        {
            return SqlHelper.Visit(ps =>
            {
                string strSql = @"insert into auth_OnlineUsers(SessionId,Token,UserId,RealName,FirstRequestTime,LastRequestTime,StartOnlineTime,RefreshToken,ExpirationTime,IsOnline,ClientIP,Longitude,Latitude,LoginType)
                                    values (@SessionId,@Token,@UserId,@RealName,@FirstRequestTime,@LastRequestTime,@StartOnlineTime,@RefreshToken,@ExpirationTime,@IsOnline,@ClientIP,@Longitude,@Latitude,@LoginType);select @@IDENTITY";
                ps.Add("@SessionId", model.SessionId);
                ps.Add("@Token", model.Token);
                ps.Add("@UserId", model.UserId);
                ps.Add("@RealName", model.RealName);
                ps.Add("@FirstRequestTime", DateTime.Now);
                ps.Add("@LastRequestTime", DateTime.Now);
                ps.Add("@StartOnlineTime", DateTime.Now);
                ps.Add("@RefreshToken", model.Token);
                ps.Add("@ExpirationTime", model.ExpirationTime);
                ps.Add("@IsOnline", model.IsOnline);
                ps.Add("@ClientIP", model.ClientIP);
                ps.Add("@Longitude", model.Longitude);
                ps.Add("@Latitude", model.Latitude);
                ps.Add("@LoginType", model.LoginType);
                string id = pubConn.ExecuteScalar(strSql, ps.ToParameters()).ToString();
                return LibConvert.StrToInt64(id);
            });
        }

		/// <summary>
		/// 更新一条数据
		/// </summary>
        public bool Update(DbConn pubConn, OnlineUserModel model)
        {
            return SqlHelper.Visit(ps =>
            {
                string field = string.Empty;
                string strSql = "update auth_OnlineUsers set Token=@Token,RefreshToken=@RefreshToken,ExpirationTime=@ExpirationTime,IsOnline=@IsOnline{0} where ID=@ID";
                ps.Add("@Token", model.Token);
                ps.Add("@RefreshToken", model.RefreshToken);
                ps.Add("@ExpirationTime", model.ExpirationTime);
                ps.Add("@IsOnline", model.IsOnline);
                if (model.IsOnline)
                {
                    field = ",LastRequestTime=@LastRequestTime";
                    ps.Add("@LastRequestTime", DateTime.Now);
                }
                ps.Add("@ID", model.ID);
                return pubConn.ExecuteSql(string.Format(strSql.ToString(), field), ps.ToParameters()) > 0;
            });
        }

        public bool UpdateExpirationTime(DbConn pubConn, string userId, DateTime expirationTime, bool isOnline = false)
	    {
            return SqlHelper.Visit(ps =>
            {
                string field = string.Empty;
                string strSql = "update auth_OnlineUsers set ExpirationTime=@ExpirationTime,IsOnline=@IsOnline{0} where UserId=@UserId";
                ps.Add("@expirationTime", expirationTime);
                ps.Add("@IsOnline", isOnline);
                if (isOnline)
                {
                    field = ",LastRequestTime=@LastRequestTime";
                    ps.Add("@LastRequestTime", DateTime.Now);
                }
                ps.Add("@UserId", userId);
                return pubConn.ExecuteSql(string.Format(strSql.ToString(), field), ps.ToParameters()) > 0;
            });
	    }

	    /// <summary>
	    /// 更新是否在线,如果在线，则更新最后请求时间
	    /// </summary>
        /// <param name="pubConn"></param>
	    /// <param name="userId"></param>
	    /// <param name="isOnline"></param>
	    /// <returns></returns>
        public bool UpdateIsOnline(DbConn pubConn, string userId, bool isOnline = false)
	    {
            return SqlHelper.Visit(ps =>
            {
                string field = string.Empty;
                string strSql = "update auth_OnlineUsers set IsOnline=@IsOnline{0} where UserId=@UserId";
                ps.Add("@IsOnline", isOnline);
                if (isOnline)
                {
                    field = ",LastRequestTime=@LastRequestTime";
                    ps.Add("@LastRequestTime", DateTime.Now);
                }
                ps.Add("@UserId", userId);
                return pubConn.ExecuteSql(string.Format(strSql.ToString(), field), ps.ToParameters()) > 0;
            });
	    }
		/// <summary>
		/// 删除一条数据
		/// </summary>
        public bool Delete(DbConn pubConn, long ID)
        {
            return SqlHelper.Visit(ps =>
            {
                string strSql = "delete from auth_OnlineUsers where ID=@ID";
                ps.Add("@ID", ID);
                return pubConn.ExecuteSql(strSql.ToString(), ps.ToParameters()) > 0;
            });
        }

        /// <summary>获取列表</summary>
        /// <param name="PubConn"></param>
        /// <param name="Mid"></param>
        /// <param name="keyword"></param>
        /// <param name="CStime"></param>
        /// <param name="CEtime"></param>
        /// <param name="state"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        //public List<ProgramMainModel> GetList(DbConn PubConn, long Mid, string keyword, string CStime, string CEtime, int pagesize, int pageindex, out int count)//, int state
        //{
        //    int _count = 0;
        //    List<ProgramMainModel> model = SqlHelper.Visit<List<ProgramMainModel>>(ps =>
        //    {
        //        string sqlwhere = "";
        //        StringBuilder sql = new StringBuilder();
        //        sql.Append("select ROW_NUMBER() over(order by T.ID desc) as rownum,T.* from ProgramMain T where 1=1 ");
        //        if (Mid != 0)
        //        {
        //            ps.Add("ID", Mid);
        //            sqlwhere += " and ( T.ID =@ID )";
        //        }
        //        if (!string.IsNullOrWhiteSpace(keyword))
        //        {
        //            ps.Add("keyword", keyword);
        //            sqlwhere += " and ( T.programName like '%'+@keyword+'%' or T.remark like '%'+@keyword+'%' )";
        //        }
        //        //if (state != -999)
        //        //{
        //        //    ps.Add("state", state);
        //        //    sqlwhere += " and T.state=@state";
        //        //}
        //        DateTime d = DateTime.Now;
        //        if (DateTime.TryParse(CStime, out d))
        //        {
        //            ps.Add("CStime", Convert.ToDateTime(CStime));
        //            sqlwhere += " and T.createTime>=@CStime";
        //        }
        //        if (DateTime.TryParse(CEtime, out d))
        //        {
        //            ps.Add("CEtime", Convert.ToDateTime(CEtime));
        //            sqlwhere += " and T.createTime<=@CEtime";
        //        }
        //        _count = Convert.ToInt32(PubConn.ExecuteScalar("select count(1) from ProgramMain T where 1=1 " + sqlwhere, ps.ToParameters()));
        //        string sqlSel = "select * from (" + sql + sqlwhere + ") A where rownum between " + ((pageindex - 1) * pagesize + 1) + " and " + pagesize * pageindex;
        //        DataTable table = PubConn.SqlToDataTable(sqlSel, ps.ToParameters());
        //        List<ProgramMainModel> _List=new List<ProgramMainModel>();
        //        foreach (DataRow dr in table.Rows)
        //        {
        //            _List.Add(ProgramMainModel.CreateModel(dr));
        //        }
        //        return _List;
        //    });
        //    count = _count;
        //    return model;
        //}

        /// <summary>获取详情</summary>
        /// <param name="pubConn"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public OnlineUserModel GetInfo(DbConn pubConn, long id)
        {
            return SqlHelper.Visit(ps =>
            {
                ps.Add("ID", id);
                string sql = "select * from auth_OnlineUsers where ID=@ID";
                DataTable table = pubConn.SqlToDataTable(sql, ps.ToParameters());
                if (table != null && table.Rows.Count > 0)
                {
                    return OnlineUserModel.CreateModel(table.Rows[0]);
                }
                else
                {
                    return null;
                }
            });
        }

        /// <summary>获取详情</summary>
        /// <param name="pubConn"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public OnlineUserModel GetInfoByUserId(DbConn pubConn, string userId)
        {
            return SqlHelper.Visit(ps =>
            {
                List<ProcedureParameter> par = new List<ProcedureParameter>()
                {
                    new ProcedureParameter("@UserId",ProcParType.VarChar,50, ParameterDirection.Input, userId)
                };
                //ps.Add("UserId", userId);
                string sql = "select top 1 * from auth_OnlineUsers where UserId=@UserId order by LastRequestTime desc";
                DataTable table = pubConn.SqlToDataTable(sql, par);//ps.ToParameters()
                if (table != null && table.Rows.Count > 0)
                {
                    return OnlineUserModel.CreateModel(table.Rows[0]);
                }
                else
                {
                    return null;
                }
            });
        }

        /// <summary>获取详情</summary>
        /// <param name="pubConn"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public OnlineUserModel GetInfoByToken(DbConn pubConn, string token)
        {
            return SqlHelper.Visit(ps =>
            {
                ps.Add("Token", token);
                string sql = "select top 1 * from auth_OnlineUsers where Token=@Token order by LastRequestTime desc";
                DataTable table = pubConn.SqlToDataTable(sql, ps.ToParameters());
                if (table != null && table.Rows.Count > 0)
                {
                    return OnlineUserModel.CreateModel(table.Rows[0]);
                }
                else
                {
                    return null;
                }
            });
        }

	}
}

